﻿using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ManiaDown.SayoApi
{
    /// <summary>
    /// 小夜镜像站API
    /// </summary>
    static class SayoApi
    {
        //
        // GET
        // 获取铺面列表
        private const string BeatmapList = "https://api.sayobot.cn/beatmaplist";
        public delegate void DownloadProgressChangedDelegate(object sender, DownloadProgressChangedEventArgs e);
        public static event DownloadProgressChangedDelegate DownloadProgressChanged;

        public static Dictionary<WebClient, Beatmap> DownloadListDic = new Dictionary<WebClient, Beatmap>();

        private static HttpClient HttpClient = new HttpClient();

        /// <summary>
        /// 获取完整版铺面下载链接
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        private static string FullMapLink(int sid) => $"https://txy1.sayobot.cn/beatmaps/download/full/{sid}";
        /// <summary>
        /// 获取无视频版铺面下载链接
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        private static string NoVideoMapLink(int sid) => $"https://txy1.sayobot.cn/beatmaps/download/novideo/{sid}";
        
        public static List<Beatmap> GetBeatmapList(BeatmapListQuery query)
        {
            var result = new List<Beatmap>();
            BeatmapListQuery.SetQueryLimit(query);
            HttpClient.GetAsync($"{BeatmapList}?{query}").ContinueWith(o =>
            {
                o.Result.Content.ReadAsStringAsync().ContinueWith(t =>
                {
                    var content = t.Result;
                    var jo = JObject.Parse(content);
                    var jmaps = jo["data"];
                    foreach(var jmap in jmaps)
                    {
                        result.Add(Beatmap.Parase((JObject)jmap));
                    }
                }).Wait();
            }).Wait();
            return result;
        }

        public static void DownloadBeatmap(Beatmap beatmap, bool fullver = false)
        {
            var webClient = new WebClient();
            DownloadListDic.Add(webClient, beatmap);
            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
            var uri = fullver ? FullMapLink(beatmap.Sid) : NoVideoMapLink(beatmap.Sid);
            webClient.DownloadFileAsync(new System.Uri(uri), @$"{beatmap}.osz");
        }

        private static void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            DownloadProgressChanged?.Invoke(sender, e);
        }

        public static void GetBeatmapList(bool prev = false)
        {
            if (prev) GetBeatmapList(BeatmapListQuery.Prev());
            else GetBeatmapList(BeatmapListQuery.Next());
        }

    }
}
